package com.youtills.core.auth.db.dao;


import com.youtills.core.admin.ILookup;
import com.youtills.core.auth.IAuth;
import com.youtills.core.auth.IAuthorizationDao;
import com.youtills.core.auth.Resource;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.HashMap;

/**
 * Created by IntelliJ IDEA.
 * User: ravi
 * Date: 8/14/12
 * Time: 10:43 AM
 * To change this template use File | Settings | File Templates.
 */
public class AuthorizationDao extends BaseAuthDao implements IAuthorizationDao {

    private static final AuthorizationDao instance = new AuthorizationDao();

    private final SqlSessionFactory sqlSessionFactory;

    private final AuthenticationDao authenticationDao;

    private AuthorizationDao() {
        super();
        sqlSessionFactory = getSqlSessionFactory();
        authenticationDao = AuthenticationDao.getInstance();
    }

    public static AuthorizationDao getInstance() {
        return instance;
    }

    public Authorization getAuthorization(IAuth auth, ILookup resourcePermissionType){
        return getAuthorization(auth, resourcePermissionType, null);
    }
    public Authorization getAuthorization(IAuth auth, ILookup resourcePermissionType, Resource targetResource){
        if(authenticationDao.validateAndExtendAuth(auth)){
            HashMap<String, Object> params = new HashMap<String, Object>(5);
            params.put("authResourceType", auth.getAuthResource().getResourceType());
            params.put("authResourceId", auth.getAuthResource().getResourceId());
            params.put("permissionId", resourcePermissionType.getId());
            if(targetResource != null){
                params.put("targetResourceType", targetResource.getResourceType());
                params.put("targetResourceId", targetResource.getResourceId());
            }else {
                params.put("targetResourceType", null);
                params.put("targetResourceId", null);
            }
            SqlSession session = sqlSessionFactory.openSession();
            try{
                Authorization authorization = session.selectOne("com.depo.quiggle.auth.db.dao.authorization-get", params);
                if(authorization != null){
                    authorization.setAuth(auth);
                    authorization.setTargetResource(targetResource);
                }
                return authorization;
            }finally{
                session.close();
            }
        }else {
            throw new RuntimeException("Invalid/Expired auth token");
        }
    }
}
